Page({
    data: {
        daysLeft: 0,
        dailyQuote: '',
        activeTab: 'timer',
        // 计时器相关
        timerMode: 'focus',
        timerDisplay: '25:00',
        isTimerRunning: false,
        timerSeconds: 1500, // 25分钟 = 1500秒
        timerInterval: null,
        todayFocusSessions: 0,
        todayFocusMinutes: 0,
        // 资料库相关
        searchQuery: '',
        selectedCategory: 'math',
        resources: [],
        filteredResources: [],
        // 计划生成器相关
        plannerData: {
            subjects: {
                math: true,
                english: true,
                politics: true,
                professional: false
            },
            hoursPerDay: 6,
            planFocus: 'balance'
        },
        generatedPlan: null,
        // 分数计算器相关
        calculatorData: {
            politics: 70,
            english: 70,
            math: 100,
            professional: 80,
            total: 320
        },
        showCalculationResult: false,
        matchingSchools: [],
        // 倒计时相关
        countdownTimer: null,
        countdownEvents: [],
        currentEvent: {
            name: '考研倒计时',
            targetDate: '2025-12-21',
            isDefault: true,
            type: 'date', // 'date'表示日期型，'time'表示精确到秒的时间型
            category: 'study', // 事件分类：study(学习)、work(工作)、life(生活)、other(其他)
            notifyEnabled: true, // 是否开启提醒
            expired: false // 新添加的事件默认未过期
        },
        showEventModal: false,
        newEvent: {
            name: '',
            targetDate: '',
            targetTime: '', // 时间型事件的时间部分
            type: 'date', // 默认为日期型
            category: 'study', // 默认分类
            notifyEnabled: true // 是否开启提醒
        },
        minDate: '', // 最小可选日期
        eventFilterCategory: 'all', // 事件过滤分类，默认显示全部
    },

    onLoad: function() {
        // 设置最小可选日期为今天
        const today = new Date();
        const minDate = today.getFullYear() + '-' +
            String(today.getMonth() + 1).padStart(2, '0') + '-' +
            String(today.getDate()).padStart(2, '0');

        this.setData({
            minDate: minDate
        });

        this.initCountdownEvents();
        this.initCountdown();
        this.initDailyQuote();
        this.initResources();
        this.loadTodayStats();
    },

    onUnload: function() {
        // 页面卸载时清除定时器
        if (this.data.countdownTimer) {
            clearInterval(this.data.countdownTimer);
        }
        if (this.data.secondTimer) {
            clearInterval(this.data.secondTimer);
        }
    },

    // 初始化倒计时事件
    initCountdownEvents: function() {
        // 获取存储的事件列表
        const events = wx.getStorageSync('countdownEvents') || [];

        // 如果没有事件，添加默认的考研倒计时
        if (events.length === 0) {
            const defaultEvent = {
                name: '考研倒计时',
                targetDate: this.getNextExamDate(),
                isDefault: true,
                type: 'date',
                category: 'study',
                notifyEnabled: true,
                expired: false
            };
            events.push(defaultEvent);
            wx.setStorageSync('countdownEvents', events);
        } else {
            // 检查所有事件的日期状态
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            events.forEach(event => {
                // 检查是否已过期
                const eventDate = new Date(event.targetDate);
                if (event.type === 'time' && event.targetTime) {
                    const eventDateTime = new Date(event.targetDate + 'T' + event.targetTime);
                    event.expired = eventDateTime <= today;
                } else {
                    event.expired = eventDate < today;
                }

                // 如果是默认事件且已过期，更新为下一年的考研日期
                if (event.isDefault && event.expired) {
                    event.targetDate = this.getNextExamDate();
                    event.expired = false;
                }
            });

            // 保存更新后的事件列表
            wx.setStorageSync('countdownEvents', events);
        }

        this.setData({
            countdownEvents: events,
            currentEvent: events[0]
        });
    },

    // 获取下一次考研日期
    getNextExamDate: function() {
        const today = new Date();
        const currentYear = today.getFullYear();
        const examDate = new Date(currentYear, 11, 21); // 12月21日

        // 如果当前日期已过今年的考试日期，则使用明年的日期
        if (today > examDate) {
            examDate.setFullYear(currentYear + 1);
        }

        return examDate.toISOString().split('T')[0];
    },

    // 显示添加事件模态框
    showAddEventModal: function() {
        // 获取今天的日期作为默认值
        const today = new Date();
        const todayFormatted = today.getFullYear() + '-' +
            String(today.getMonth() + 1).padStart(2, '0') + '-' +
            String(today.getDate()).padStart(2, '0');

        // 获取当前时间作为默认值
        const currentHour = String(today.getHours()).padStart(2, '0');
        const currentMinute = String(today.getMinutes()).padStart(2, '0');
        const timeFormatted = `${currentHour}:${currentMinute}`;

        this.setData({
            showEventModal: true,
            newEvent: {
                name: '',
                targetDate: todayFormatted,
                targetTime: timeFormatted,
                type: 'date', // 默认为日期型
                category: 'study', // 默认分类
                notifyEnabled: true // 默认开启提醒
            },
            minDate: todayFormatted
        });
    },

    // 切换事件类型
    switchEventType: function(e) {
        const type = e.currentTarget.dataset.type;
        this.setData({
            'newEvent.type': type
        });
    },

    // 选择时间
    onTimeChange: function(e) {
        this.setData({
            'newEvent.targetTime': e.detail.value
        });
    },

    // 隐藏添加事件模态框
    hideAddEventModal: function() {
        this.setData({
            showEventModal: false
        });
    },

    // 输入事件名称
    onEventNameInput: function(e) {
        this.setData({
            'newEvent.name': e.detail.value
        });
    },

    // 选择目标日期
    onDateChange: function(e) {
        this.setData({
            'newEvent.targetDate': e.detail.value
        });
    },

    // 选择事件分类
    onCategoryChange: function(e) {
        this.setData({
            'newEvent.category': e.currentTarget.dataset.category
        });
    },

    // 切换提醒开关
    toggleNotify: function(e) {
        this.setData({
            'newEvent.notifyEnabled': !this.data.newEvent.notifyEnabled
        });
    },

    // 过滤事件分类
    filterEventsByCategory: function(e) {
        const category = e.currentTarget.dataset.category;
        this.setData({
            eventFilterCategory: category
        });
    },

    // 添加新事件
    addNewEvent: function() {
        const { name, targetDate, targetTime, type, category, notifyEnabled } = this.data.newEvent;

        if (!name) {
            wx.showToast({
                title: '请填写事件名称',
                icon: 'none'
            });
            return;
        }

        if (type === 'date' && !targetDate) {
            wx.showToast({
                title: '请选择日期',
                icon: 'none'
            });
            return;
        }

        if (type === 'time' && (!targetDate || !targetTime)) {
            wx.showToast({
                title: '请选择完整的日期和时间',
                icon: 'none'
            });
            return;
        }

        // 验证日期是否为未来日期
        const today = new Date();
        today.setHours(0, 0, 0, 0); // 设置为当天的开始时间
        const selectedDate = new Date(targetDate);

        if (selectedDate < today) {
            wx.showToast({
                title: '请选择未来的日期',
                icon: 'none'
            });
            return;
        }

        // 如果是时间型事件，验证时间是否合法
        if (type === 'time') {
            const selectedDateTime = new Date(targetDate + 'T' + targetTime);
            if (selectedDateTime <= new Date()) {
                wx.showToast({
                    title: '请选择未来的时间',
                    icon: 'none'
                });
                return;
            }
        }

        const events = [...this.data.countdownEvents];
        events.push({
            name,
            targetDate,
            targetTime: type === 'time' ? targetTime : '',
            type,
            category,
            notifyEnabled,
            isDefault: false,
            expired: false // 新添加的事件默认未过期
        });

        wx.setStorageSync('countdownEvents', events);

        this.setData({
            countdownEvents: events,
            showEventModal: false
        });

        // 切换到新添加的事件
        this.switchEvent(events.length - 1);
    },

    // 切换倒计时事件
    switchEvent: function(e) {
        // 支持两种调用方式：直接传入索引或者通过事件对象
        let index;
        if (typeof e === 'number') {
            index = e;
        } else {
            index = e.currentTarget.dataset.index;
        }

        const event = this.data.countdownEvents[index];
        this.setData({
            currentEvent: event
        });

        // 根据事件类型更新倒计时
        if (event.type === 'time') {
            this.updateCountdown(event.targetDate, event.targetTime);
        } else {
            this.updateCountdown(new Date(event.targetDate), null);
        }
    },

    // 删除事件
    deleteEvent: function(e) {
        const index = e.currentTarget.dataset.index;
        const events = [...this.data.countdownEvents];
        const event = events[index];

        // 默认事件不能删除
        if (event.isDefault) {
            wx.showToast({
                title: '默认事件不能删除',
                icon: 'none'
            });
            return;
        }

        wx.showModal({
            title: '确认删除',
            content: '确定要删除这个倒计时事件吗？',
            success: (res) => {
                if (res.confirm) {
                    // 删除事件
                    events.splice(index, 1);

                    // 保存更新后的事件列表
                    wx.setStorageSync('countdownEvents', events);

                    // 更新状态
                    this.setData({
                        countdownEvents: events
                    });

                    // 如果删除的是当前事件，切换到第一个事件
                    if (this.data.currentEvent.name === event.name) {
                        this.switchEvent(0);
                    }
                }
            }
        });
    },

    // 初始化倒计时
    initCountdown: function() {
        // 获取当前选中的事件信息
        const event = this.data.currentEvent;
        let targetDate, targetTime;

        if (event.type === 'time') {
            targetDate = event.targetDate;
            targetTime = event.targetTime;
        } else {
            targetDate = new Date(event.targetDate);
            targetTime = null;
        }

        // 立即计算一次
        this.updateCountdown(targetDate, targetTime);

        // 设置定时器，每小时更新一次（对于日期型事件）
        if (this.data.countdownTimer) {
            clearInterval(this.data.countdownTimer);
        }

        const countdownTimer = setInterval(() => {
            if (this.data.currentEvent.type === 'date') {
                this.updateCountdown(new Date(this.data.currentEvent.targetDate), null);
            }
        }, 3600000); // 3600000毫秒 = 1小时

        this.setData({
            countdownTimer: countdownTimer
        });
    },

    // 更新倒计时
    updateCountdown: function(targetDate, targetTime) {
        const today = new Date();
        let diffTime, diffDays, diffHours, diffMinutes, diffSeconds;
        let displayText = '';
        let isExpired = false;

        if (targetTime) {
            // 精确到秒的时间型事件
            const targetDateTime = new Date(targetDate + 'T' + targetTime);
            diffTime = targetDateTime - today;

            if (diffTime <= 0) {
                displayText = '0天0时0分0秒';
                isExpired = true;

                this.setData({
                    daysLeft: displayText
                });

                // 事件到期提醒 - 仅在事件未标记为已过期时提醒
                if (this.data.currentEvent.name &&
                    this.data.currentEvent.notifyEnabled &&
                    !this.data.currentEvent.expired) {

                    // 更新事件为已过期状态
                    const events = [...this.data.countdownEvents];
                    const currentIndex = events.findIndex(e => e.name === this.data.currentEvent.name);
                    if (currentIndex >= 0) {
                        events[currentIndex].expired = true;
                        wx.setStorageSync('countdownEvents', events);

                        this.setData({
                            countdownEvents: events,
                            'currentEvent.expired': true
                        });

                        // 显示到期提醒
                        this.triggerEventNotification(this.data.currentEvent.name);
                    }
                }
                return;
            }

            // 事件即将到期检查（1小时内）
            if (diffTime <= 3600000 && diffTime > 3540000 && this.data.currentEvent.notifyEnabled) {
                this.triggerEventReminder(this.data.currentEvent.name, '1小时');
            }

            // 计算天、时、分、秒
            diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
            diffHours = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            diffMinutes = Math.floor((diffTime % (1000 * 60 * 60)) / (1000 * 60));
            diffSeconds = Math.floor((diffTime % (1000 * 60)) / 1000);

            displayText = `${diffDays}天${diffHours}时${diffMinutes}分${diffSeconds}秒`;

            // 对于精确到秒的事件，需要每秒更新
            if (!this.data.secondTimer) {
                const secondTimer = setInterval(() => {
                    if (this.data.currentEvent.type === 'time') {
                        this.updateCountdown(this.data.currentEvent.targetDate, this.data.currentEvent.targetTime);
                    }
                }, 1000);

                this.setData({
                    secondTimer: secondTimer
                });
            }
        } else {
            // 普通日期型事件
            diffTime = targetDate - today;

            // 如果目标日期已过，显示0天
            diffDays = diffTime <= 0 ? 0 : Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            displayText = diffDays;

            if (diffDays === 0) {
                isExpired = true;

                // 如果目标日期已过，显示提示 - 仅在事件未标记为已过期时提醒
                if (this.data.currentEvent.name &&
                    this.data.currentEvent.notifyEnabled &&
                    !this.data.currentEvent.expired) {

                    // 更新事件为已过期状态
                    const events = [...this.data.countdownEvents];
                    const currentIndex = events.findIndex(e => e.name === this.data.currentEvent.name);
                    if (currentIndex >= 0) {
                        events[currentIndex].expired = true;
                        wx.setStorageSync('countdownEvents', events);

                        this.setData({
                            countdownEvents: events,
                            'currentEvent.expired': true
                        });

                        // 显示到期提醒
                        this.triggerEventNotification(this.data.currentEvent.name);
                    }
                }
            }

            // 事件即将到期检查（1天内）
            else if (diffDays === 1 && this.data.currentEvent.notifyEnabled) {
                const hours = Math.floor((diffTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                if (hours <= 1) { // 最后一天的第一小时内提醒
                    this.triggerEventReminder(this.data.currentEvent.name, '1天');
                }
            }

            // 清除秒级定时器
            if (this.data.secondTimer) {
                clearInterval(this.data.secondTimer);
                this.setData({
                    secondTimer: null
                });
            }
        }

        this.setData({
            daysLeft: displayText,
            'currentEvent.isExpired': isExpired
        });
    },

    // 触发事件到期通知
    triggerEventNotification: function(eventName) {
        // 播放提示音
        const innerAudioContext = wx.createInnerAudioContext();
        innerAudioContext.src = '/assets/sounds/notification.mp3'; // 确保有这个音频文件
        innerAudioContext.play();

        // 显示通知
        wx.showModal({
            title: '事件已到期',
            content: `"${eventName}" 已到期！`,
            confirmText: '知道了',
            showCancel: false
        });
    },

    // 触发事件即将到期提醒
    triggerEventReminder: function(eventName, timeLeft) {
        wx.showToast({
            title: `"${eventName}" 将在${timeLeft}内到期`,
            icon: 'none',
            duration: 3000
        });
    },

    // 初始化每日激励语
    initDailyQuote: function() {
        const quotes = [
            "考研路上，每一步都是进步",
            "今天的努力，是明天的收获",
            "坚持就是胜利",
            "相信自己，你比想象中更强大",
            "学习是一个积累的过程",
            "不要等待机会，而要创造机会",
            "成功不是将来才有的，而是从决定去做的那一刻起就已经开始的"
        ];

        const randomIndex = Math.floor(Math.random() * quotes.length);
        this.setData({
            dailyQuote: quotes[randomIndex]
        });
    },

    // 切换选项卡
    switchTab: function(e) {
        const tab = e.currentTarget.dataset.tab;
        this.setData({
            activeTab: tab
        });
    },

    // ===== 计时器相关函数 =====
    // 设置计时器模式
    setTimerMode: function(e) {
        const mode = e.currentTarget.dataset.mode;
        let seconds = 1500; // 默认25分钟
        let display = '25:00';

        if (mode === 'short') {
            seconds = 300; // 5分钟
            display = '05:00';
        } else if (mode === 'long') {
            seconds = 900; // 15分钟
            display = '15:00';
        }

        // 如果计时器正在运行，先停止
        if (this.data.isTimerRunning) {
            clearInterval(this.data.timerInterval);
        }

        this.setData({
            timerMode: mode,
            timerSeconds: seconds,
            timerDisplay: display,
            isTimerRunning: false
        });
    },

    // 开始/暂停计时器
    toggleTimer: function() {
        if (this.data.isTimerRunning) {
            // 暂停计时器
            clearInterval(this.data.timerInterval);
            this.setData({
                isTimerRunning: false
            });
        } else {
            // 开始计时器
            const timerInterval = setInterval(() => {
                let seconds = this.data.timerSeconds - 1;

                if (seconds < 0) {
                    // 计时结束
                    clearInterval(this.data.timerInterval);
                    this.handleTimerComplete();
                    return;
                }

                // 更新计时器显示
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;
                const display = `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;

                this.setData({
                    timerSeconds: seconds,
                    timerDisplay: display
                });
            }, 1000);

            this.setData({
                timerInterval: timerInterval,
                isTimerRunning: true
            });
        }
    },

    // 重置计时器
    resetTimer: function() {
        if (this.data.isTimerRunning) {
            clearInterval(this.data.timerInterval);
        }

        let seconds = 1500; // 默认25分钟
        let display = '25:00';

        if (this.data.timerMode === 'short') {
            seconds = 300; // 5分钟
            display = '05:00';
        } else if (this.data.timerMode === 'long') {
            seconds = 900; // 15分钟
            display = '15:00';
        }

        this.setData({
            timerSeconds: seconds,
            timerDisplay: display,
            isTimerRunning: false
        });
    },

    // 计时器完成
    handleTimerComplete: function() {
        // 播放提示音（微信小程序需要引入音频文件）
        // const innerAudioContext = wx.createInnerAudioContext();
        // innerAudioContext.src = '/sounds/timer-complete.mp3';
        // innerAudioContext.play();

        // 显示通知
        wx.showToast({
            title: this.data.timerMode === 'focus' ? '专注时间结束，休息一下吧' : '休息结束，继续学习吧',
            icon: 'none',
            duration: 2000
        });

        // 如果是专注模式，记录完成的专注次数和时间
        if (this.data.timerMode === 'focus') {
            // 获取今日数据
            let sessions = this.data.todayFocusSessions + 1;
            let minutes = this.data.todayFocusMinutes + 25;

            this.setData({
                todayFocusSessions: sessions,
                todayFocusMinutes: minutes
            });

            // 保存到本地存储
            this.saveTodayStats(sessions, minutes);
        }

        // 重置计时器
        this.resetTimer();
    },

    // 加载今日统计
    loadTodayStats: function() {
        const today = new Date().toISOString().split('T')[0]; // 格式：YYYY-MM-DD
        const statsKey = `focusStats_${today}`;

        const stats = wx.getStorageSync(statsKey) || { sessions: 0, minutes: 0 };

        this.setData({
            todayFocusSessions: stats.sessions,
            todayFocusMinutes: stats.minutes
        });
    },

    // 保存今日统计
    saveTodayStats: function(sessions, minutes) {
        const today = new Date().toISOString().split('T')[0]; // 格式：YYYY-MM-DD
        const statsKey = `focusStats_${today}`;

        wx.setStorageSync(statsKey, {
            sessions: sessions,
            minutes: minutes
        });
    },

    // ===== 资料库相关函数 =====
    // 初始化资源数据
    initResources: function() {
        // 模拟资料数据
        const resources = [{
                id: 1,
                category: 'math',
                title: '高数常用公式',
                content: '<div><p>1. 导数公式：</p><p>(uv)′ = u′v + uv′</p><p>(u/v)′ = (u′v - uv′)/v²</p><p>2. 积分公式：</p><p>∫sin(x)dx = -cos(x) + C</p><p>∫cos(x)dx = sin(x) + C</p><p>∫e^x dx = e^x + C</p></div>',
                expanded: false
            },
            {
                id: 2,
                category: 'math',
                title: '线性代数基本概念',
                content: '<div><p>1. 矩阵：由m×n个数排成的m行n列的数表。</p><p>2. 行列式：是一个n阶方阵的n次多项式函数，记为det(A)或|A|。</p><p>3. 特征值：若存在非零向量x使得Ax=λx，则称λ为矩阵A的特征值。</p></div>',
                expanded: false
            },
            {
                id: 3,
                category: 'english',
                title: '考研英语高频词汇',
                content: '<div><p>1. accommodate: v. 容纳；提供住宿；使适应</p><p>2. controversial: adj. 有争议的</p><p>3. differentiate: v. 区分；使不同</p><p>4. inevitable: adj. 不可避免的</p><p>5. obsolete: adj. 过时的，废弃的</p><p>6. pragmatic: adj. 实用的，务实的</p></div>',
                expanded: false
            },
            {
                id: 4,
                category: 'english',
                title: '常见长难句解析技巧',
                content: '<div><p>1. 找主干：找出句子的主语、谓语和宾语</p><p>2. 识别从句：定语从句、状语从句、名词性从句</p><p>3. 分析修饰关系：形容词、副词、介词短语等修饰成分</p><p>4. 理解逻辑关系：因果、转折、递进、并列等</p></div>',
                expanded: false
            },
            {
                id: 5,
                category: 'politics',
                title: '马克思主义哲学核心观点',
                content: '<div><p>1. 物质决定意识，意识能动地反作用于物质</p><p>2. 实践是检验真理的唯一标准</p><p>3. 矛盾是事物发展的根本动力</p><p>4. 量变引起质变，质变是量变的必然结果</p><p>5. 否定之否定规律揭示了事物发展的方向和道路</p></div>',
                expanded: false
            },
            {
                id: 6,
                category: 'politics',
                title: '中国特色社会主义理论体系',
                content: '<div><p>1. 邓小平理论</p><p>2. "三个代表"重要思想</p><p>3. 科学发展观</p><p>4. 习近平新时代中国特色社会主义思想</p><p>其中习近平新时代中国特色社会主义思想是马克思主义中国化的最新成果。</p></div>',
                expanded: false
            },
            {
                id: 7,
                category: 'professional',
                title: '计算机网络OSI七层模型',
                content: '<div><p>1. 物理层：负责比特流的传输</p><p>2. 数据链路层：负责物理寻址和差错检测</p><p>3. 网络层：负责路由选择和IP寻址</p><p>4. 传输层：负责端到端的连接</p><p>5. 会话层：建立、管理和终止会话</p><p>6. 表示层：数据格式转换和加密解密</p><p>7. 应用层：为应用程序提供服务</p></div>',
                expanded: false
            },
            {
                id: 8,
                category: 'professional',
                title: '数据结构基础',
                content: '<div><p>1. 线性结构：数组、链表、栈、队列</p><p>2. 树形结构：二叉树、平衡树、B树</p><p>3. 图形结构：有向图、无向图</p><p>4. 散列结构：哈希表</p><p>常见算法复杂度：快速排序O(nlogn)，二分查找O(logn)</p></div>',
                expanded: false
            }
        ];

        this.setData({
            resources: resources,
            selectedCategory: 'all', // 默认显示全部分类
            filteredResources: this.filterResources(resources, 'all', '') // 默认筛选全部
        });
    },

    // 资源搜索
    onSearchInput: function(e) {
        const query = e.detail.value.trim().toLowerCase();

        this.setData({
            searchQuery: query,
            filteredResources: this.filterResources(this.data.resources, this.data.selectedCategory, query)
        });
    },

    // 过滤资源
    filterResources: function(resources, category, query) {
        return resources.filter(item => {
            // 如果没有选择分类，则显示所有资源
            const matchCategory = category === 'all' || item.category === category;

            // 如果没有搜索词，则只根据分类过滤
            if (!query) {
                return matchCategory;
            }

            // 否则，搜索标题和内容中的匹配项
            const matchQuery =
                item.title.toLowerCase().includes(query) ||
                this.stripHtml(item.content).toLowerCase().includes(query);

            return matchCategory && matchQuery;
        });
    },

    // 去除HTML标签，用于纯文本搜索
    stripHtml: function(html) {
        return html.replace(/<[^>]*>?/gm, '');
    },

    // 选择分类
    selectCategory: function(e) {
        const category = e.currentTarget.dataset.category;

        this.setData({
            selectedCategory: category,
            filteredResources: this.filterResources(this.data.resources, category, this.data.searchQuery)
        });
    },

    // 展开/折叠资源
    toggleResource: function(e) {
        const id = e.currentTarget.dataset.id;
        const resources = this.data.resources.map(item => {
            if (item.id === id) {
                return {
                    ...item,
                    expanded: !item.expanded
                };
            }
            return item;
        });

        this.setData({
            resources: resources,
            filteredResources: this.filterResources(resources, this.data.selectedCategory, this.data.searchQuery)
        });
    },

    // ===== 计划生成器相关函数 =====
    // 切换科目
    toggleSubject: function(e) {
        const subject = e.currentTarget.dataset.subject;
        const subjects = this.data.plannerData.subjects;

        subjects[subject] = !subjects[subject];

        this.setData({
            'plannerData.subjects': subjects
        });
    },

    // 设置每日学习时间
    setHoursPerDay: function(e) {
        this.setData({
            'plannerData.hoursPerDay': e.detail.value
        });
    },

    // 设置计划重点
    setPlanFocus: function(e) {
        this.setData({
            'plannerData.planFocus': e.detail.value
        });
    },

    // 生成计划
    generatePlan: function() {
        // 检查是否选择了至少一个科目
        const subjects = this.data.plannerData.subjects;
        if (!subjects.math && !subjects.english && !subjects.politics && !subjects.professional) {
            wx.showToast({
                title: '请至少选择一个科目',
                icon: 'none'
            });
            return;
        }

        // 生成计划
        const planFocus = this.data.plannerData.planFocus;
        const hoursPerDay = this.data.plannerData.hoursPerDay;

        // 创建计划结构
        const plan = {
            sections: [{
                    title: '每日学习安排',
                    items: []
                },
                {
                    title: '每周复习计划',
                    items: []
                },
                {
                    title: '学习建议',
                    items: []
                }
            ]
        };

        // 填充学习安排
        if (subjects.math) {
            plan.sections[0].items.push(`数学: ${this.calculateSubjectTime(hoursPerDay, 'math', planFocus)}小时/天`);
        }
        if (subjects.english) {
            plan.sections[0].items.push(`英语: ${this.calculateSubjectTime(hoursPerDay, 'english', planFocus)}小时/天`);
        }
        if (subjects.politics) {
            plan.sections[0].items.push(`政治: ${this.calculateSubjectTime(hoursPerDay, 'politics', planFocus)}小时/天`);
        }
        if (subjects.professional) {
            plan.sections[0].items.push(`专业课: ${this.calculateSubjectTime(hoursPerDay, 'professional', planFocus)}小时/天`);
        }

        // 填充每周复习计划
        plan.sections[1].items.push('周一至周五: 按每日计划执行');
        plan.sections[1].items.push('周六: 复习本周重点内容，查漏补缺');
        plan.sections[1].items.push('周日: 进行模拟测试，总结本周学习情况');

        // 根据计划重点生成学习建议
        if (planFocus === 'balance') {
            plan.sections[2].items.push('各科均衡发展，注重打好基础');
            plan.sections[2].items.push('每天给各科分配相对平均的时间');
            plan.sections[2].items.push('定期做综合测试，评估各科学习情况');
        } else if (planFocus === 'short') {
            plan.sections[2].items.push('短期内集中突破重点科目');
            plan.sections[2].items.push('每周重点轮换，确保各科都有突破');
            plan.sections[2].items.push('注重攻克难点，提高解题速度');
        } else if (planFocus === 'weak') {
            plan.sections[2].items.push('优先补足薄弱科目和知识点');
            plan.sections[2].items.push('定期做模拟题，找出不足之处');
            plan.sections[2].items.push('保持优势科目的复习频率，重点提升弱势科目');
        }

        // 更新状态
        this.setData({
            generatedPlan: plan
        });
    },

    // 计算科目时间分配
    calculateSubjectTime: function(totalHours, subject, focus) {
        const weights = {
            balance: {
                math: 0.3,
                english: 0.25,
                politics: 0.2,
                professional: 0.25
            },
            short: {
                math: 0.4,
                english: 0.3,
                politics: 0.1,
                professional: 0.2
            },
            weak: {
                // 这里假设数学是弱项
                math: 0.4,
                english: 0.2,
                politics: 0.2,
                professional: 0.2
            }
        };

        // 计算科目权重
        const weight = weights[focus][subject];

        // 计算时间
        const hours = totalHours * weight;

        return hours.toFixed(1);
    },

    // 分享计划
    sharePlan: function() {
        wx.showToast({
            title: '分享功能开发中',
            icon: 'none'
        });
    },

    // ===== 分数计算器相关函数 =====
    // 设置分数
    setScore: function(e) {
        const subject = e.currentTarget.dataset.subject;
        const value = e.detail.value;

        // 更新数据
        const data = {};
        data[`calculatorData.${subject}`] = value;

        this.setData(data);
    },

    // 计算总分
    calculateTotal: function() {
        const data = this.data.calculatorData;

        // 转换为数字并计算总分
        const politics = parseInt(data.politics) || 0;
        const english = parseInt(data.english) || 0;
        const math = parseInt(data.math) || 0;
        const professional = parseInt(data.professional) || 0;

        const total = politics + english + math + professional;

        // 获取匹配的学校
        const matchingSchools = this.getMatchingSchools(total);

        // 更新状态
        this.setData({
            'calculatorData.total': total,
            matchingSchools: matchingSchools,
            showCalculationResult: true
        });
    },

    // 获取匹配的学校
    getMatchingSchools: function(total) {
        // 模拟数据：学校名称、分数线、专业要求、地理位置等
        const schools = [{
                name: '北京大学',
                score: 380,
                location: '北京',
                requirements: {
                    math: 120,
                    english: 70,
                    politics: 70,
                    professional: 120
                }
            },
            {
                name: '清华大学',
                score: 385,
                location: '北京',
                requirements: {
                    math: 125,
                    english: 70,
                    politics: 70,
                    professional: 120
                }
            },
            {
                name: '复旦大学',
                score: 370,
                location: '上海',
                requirements: {
                    math: 115,
                    english: 70,
                    politics: 70,
                    professional: 115
                }
            },
            {
                name: '上海交通大学',
                score: 365,
                location: '上海',
                requirements: {
                    math: 115,
                    english: 65,
                    politics: 65,
                    professional: 120
                }
            },
            {
                name: '浙江大学',
                score: 355,
                location: '浙江',
                requirements: {
                    math: 110,
                    english: 65,
                    politics: 65,
                    professional: 115
                }
            },
            {
                name: '南京大学',
                score: 350,
                location: '江苏',
                requirements: {
                    math: 110,
                    english: 65,
                    politics: 65,
                    professional: 110
                }
            },
            {
                name: '武汉大学',
                score: 340,
                location: '湖北',
                requirements: {
                    math: 105,
                    english: 60,
                    politics: 60,
                    professional: 115
                }
            },
            {
                name: '中国人民大学',
                score: 360,
                location: '北京',
                requirements: {
                    math: 110,
                    english: 70,
                    politics: 70,
                    professional: 110
                }
            },
            {
                name: '中山大学',
                score: 345,
                location: '广东',
                requirements: {
                    math: 105,
                    english: 65,
                    politics: 65,
                    professional: 110
                }
            },
            {
                name: '华中科技大学',
                score: 335,
                location: '湖北',
                requirements: {
                    math: 105,
                    english: 60,
                    politics: 60,
                    professional: 110
                }
            }
        ];

        // 获取各科分数
        const scores = {
            math: parseInt(this.data.calculatorData.math) || 0,
            english: parseInt(this.data.calculatorData.english) || 0,
            politics: parseInt(this.data.calculatorData.politics) || 0,
            professional: parseInt(this.data.calculatorData.professional) || 0
        };

        // 根据总分和单科分数匹配学校
        return schools.map(school => {
            let chance = '低';
            let matchReason = [];

            // 检查总分是否达到要求
            if (total >= school.score + 20) {
                chance = '高';
                matchReason.push('总分超出要求20分以上');
            } else if (total >= school.score) {
                chance = '中';
                matchReason.push('总分达到要求');
            }

            // 检查单科是否达到要求
            if (scores.math >= school.requirements.math) {
                matchReason.push('数学达标');
            }
            if (scores.english >= school.requirements.english) {
                matchReason.push('英语达标');
            }
            if (scores.politics >= school.requirements.politics) {
                matchReason.push('政治达标');
            }
            if (scores.professional >= school.requirements.professional) {
                matchReason.push('专业课达标');
            }

            // 如果单科都达标，提高录取可能性
            if (matchReason.length >= 3) {
                if (chance === '低') chance = '中';
                else if (chance === '中') chance = '高';
            }

            return {
                name: school.name,
                score: school.score,
                location: school.location,
                chance: chance,
                matchReason: matchReason.join('，')
            };
        }).sort((a, b) => {
            // 按录取可能性排序
            const chanceOrder = { '高': 0, '中': 1, '低': 2 };
            return chanceOrder[a.chance] - chanceOrder[b.chance] || b.score - a.score;
        }).slice(0, 5); // 只显示前5个
    }
});